package com.bjsxt.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bjsxt.constants.Constants;
import com.bjsxt.domain.*;
import com.bjsxt.dto.CareHistoryDto;
import com.bjsxt.dto.CareOrderDto;
import com.bjsxt.dto.CareOrderFormDto;
import com.bjsxt.dto.CareOrderItemDto;
import com.bjsxt.mapper.*;
import com.bjsxt.service.CareHistoryService;
import com.bjsxt.service.MedicinesService;
import com.bjsxt.utils.IdGeneratorSnowflake;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.constraints.NotEmpty;
import java.math.BigDecimal;
import java.util.List;

/**
 * 病历管理service接口实现类
 */
@Service
public class CareHistoryServiceImpl implements CareHistoryService {

    @Autowired
    private CareHistoryMapper careHistoryMapper;

    @Autowired
    private CareOrderMapper careOrderMapper;

    @Autowired
    private CareOrderItemMapper careOrderItemMapper;

    @Autowired
    private RegistrationMapper registrationMapper;

    @Autowired
    private OrderChargeItemMapper orderChargeItemMapper;

    @Reference
    private MedicinesService medicinesService;

    /**
     * 根据患者id查询患者病例
     *
     * @param patientId
     * @return
     */
    @Override
    public List<CareHistory> queryCareHistoryByPatientId(String patientId) {
        QueryWrapper<CareHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(CareHistory.COL_PATIENT_ID, patientId);
        return this.careHistoryMapper.selectList(queryWrapper);
    }

    /**
     * 保存或更新病例信息
     *
     * @param careHistoryDto
     * @return
     */
    @Override
    public CareHistory saveOrUpdateCareHistory(CareHistoryDto careHistoryDto) {
        CareHistory careHistory = new CareHistory();
        BeanUtil.copyProperties(careHistoryDto, careHistory);
        if (StringUtils.isNotBlank(careHistory.getChId())) {
            this.careHistoryMapper.updateById(careHistory);
        } else {
            careHistory.setChId(IdGeneratorSnowflake.generatorIdWithProfix(Constants.ID_PROFIX_CH));
            this.careHistoryMapper.insert(careHistory);
        }
        return careHistory;
    }

    /**
     * 根据挂号单id查询对应的病例信息
     *
     * @param regId
     * @return
     */
    @Override
    public CareHistory queryCareHistoryByRegId(String regId) {
        QueryWrapper<CareHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(CareHistory.COL_REG_ID, regId);
        return this.careHistoryMapper.selectOne(queryWrapper);
    }

    /**
     * 根据病例信息查询处方信息
     *
     * @param chId
     * @return
     */
    @Override
    public List<CareOrder> queryCareOrdersByChId(String chId) {
        QueryWrapper<CareOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(CareOrder.COL_CH_ID, chId);
        return this.careOrderMapper.selectList(queryWrapper);
    }

    /**
     * 根据处方id查询处方详情id
     *
     * @param coId
     * @return
     */
    @Override
    public List<CareOrderItem> queryCareOrderItemsByCoId(String coId) {
        QueryWrapper<CareOrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(CareOrderItem.COL_CO_ID, coId);
        return this.careOrderItemMapper.selectList(queryWrapper);
    }

    /**
     * 根据病例id查询病例信息
     *
     * @param chId
     * @return
     */
    @Override
    public CareHistory queryCareHistoryByChId(String chId) {
        return this.careHistoryMapper.selectById(chId);
    }

    /**
     * 保存处方及详情信息
     *
     * @param careOrderFormDto
     * @return
     */
    @Override
    public int saveCareOrderItem(CareOrderFormDto careOrderFormDto) {
        CareOrderDto careOrderDto = careOrderFormDto.getCareOrder();
        CareOrder careOrder = new CareOrder();
        BeanUtil.copyProperties(careOrderDto, careOrder);
        careOrder.setCreateBy(careOrderDto.getSimpleUser().getUserName());
        careOrder.setCreateTime(DateUtil.date());
        int i = this.careOrderMapper.insert(careOrder);
        @NotEmpty(message = "处方详情不能为空") List<CareOrderItemDto> careOrderItems = careOrderFormDto.getCareOrderItems();
//        保存详情数据
        for (CareOrderItemDto careOrderItemDto : careOrderItems) {
            CareOrderItem careOrderItem = new CareOrderItem();
            BeanUtil.copyProperties(careOrderItemDto, careOrderItem);
            careOrderItem.setCoId(careOrder.getCoId());
            careOrderItem.setCreateTime(DateUtil.date());
            careOrderItem.setStatus(Constants.ORDER_DETAILS_STATUS_0);//未支付
            careOrderItem.setItemId(IdGeneratorSnowflake.generatorIdWithProfix(Constants.ID_PROFIX_ITEM));
            this.careOrderItemMapper.insert(careOrderItem);
        }
        return i;
    }

    /**
     * 根据处方详情id查询处方详情数据
     *
     * @param itemId
     * @return
     */
    @Override
    public CareOrderItem queryCareOrderItemByItemId(String itemId) {
        return this.careOrderItemMapper.selectById(itemId);
    }

    /**
     * 根据详情id删除详情信息
     *
     * @param itemId
     * @return
     */
    @Override
    public int deleteCareOrderItemByItemId(String itemId) {
//        如果进行删除，需要更新careOrder主表的all_amount
        CareOrderItem careOrderItem = this.careOrderItemMapper.selectById(itemId);
        String coId = careOrderItem.getCoId();
//        删除
        int i = this.careOrderItemMapper.deleteById(coId);
//        再根据coId查询存在的详情数据
        QueryWrapper<CareOrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(CareOrderItem.COL_CO_ID, coId);
        List<CareOrderItem> careOrderItems = this.careOrderItemMapper.selectList(queryWrapper);
        if (careOrderItems != null && careOrderItems.size() > 0) {
//            重新计算总价格
            BigDecimal allDecimal = new BigDecimal("0");
            for (CareOrderItem orderItem : careOrderItems) {
                allDecimal = allDecimal.add(orderItem.getAmount());
            }
//            再根据coId查询主表的数据
            CareOrder careOrder = this.careOrderMapper.selectById(coId);
//            更新主表的数据
            careOrder.setAllAmount(allDecimal);
            this.careOrderMapper.updateById(careOrder);
        } else {
//            说明没有详情信息，可以直接删除主表中的数据
            this.careOrderMapper.deleteById(coId);
        }
        return i;
    }

    /**
     * 完成就诊
     *
     * @param regId
     * @return
     */
    @Override
    public int visitComplete(String regId) {
        Registration registration = new Registration();
        registration.setRegistrationId(regId);
        registration.setRegistrationStatus(Constants.REG_STATUS_3);
        return this.registrationMapper.updateById(registration);
    }

    /**
     * 根据处方id查询处方详情信息
     *
     * @param coId
     * @param status
     * @return
     */
    @Override
    public List<CareOrderItem> queryCareOrderItemsByCoId(String coId, String status) {
        QueryWrapper<CareOrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(CareOrderItem.COL_CO_ID, coId);
        queryWrapper.eq(StringUtils.isNotBlank(status), CareOrderItem.COL_STATUS, status);
        return this.careOrderItemMapper.selectList(queryWrapper);
    }

    /**
     * 发药
     * 【逻辑】
     * 1、根据详情id查询处方项目
     * 2、扣减库存（如果库存够就扣减，返回受影响行数，如果不够就返回0）
     * 3、如果返回0则说明库存不够，停止发药
     * 4、如果返回>0，更新处方详情，状态为3
     *
     * @param itemIds
     * @return
     */
    @Override
    public String doMedicine(List<String> itemIds) {
        QueryWrapper<CareOrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(CareOrderItem.COL_ITEM_ID, itemIds);
        List<CareOrderItem> careOrderItems = this.careOrderItemMapper.selectList(queryWrapper);
        StringBuffer sb = new StringBuffer();
        for (CareOrderItem careOrderItem : careOrderItems) {
//            库存扣减
            int i = this.medicinesService.deductionMedicinesStorage(Long.valueOf(careOrderItem.getItemRefId()), careOrderItem.getNum().longValue());
            if (i > 0) {
//                说明库存够，更新处方详情状态
                careOrderItem.setStatus(Constants.ORDER_DETAILS_STATUS_3);
                this.careOrderItemMapper.updateById(careOrderItem);
//                更新收费详情状态
                OrderChargeItem orderChargeItem = new OrderChargeItem();
                orderChargeItem.setItemId(careOrderItem.getItemId());
                orderChargeItem.setStatus(Constants.ORDER_DETAILS_STATUS_3);
                this.orderChargeItemMapper.updateById(orderChargeItem);
            } else {
                sb.append("【" + careOrderItem.getItemName() + "】发药失败");
            }
        }
        if (StringUtils.isBlank(sb.toString())) {
            return null;
        } else {
            sb.append("原因：库存不足");
            return sb.toString();
        }
    }

    /**
     * 根据处方id查询处方详情
     *
     * @param coId
     * @return
     */
    @Override
    public CareOrder queryCareOrderByCoId(String coId) {
        return this.careOrderMapper.selectById(coId);
    }

}
